package m.store.action;

import m.appserver.AuthInfoUtil;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.Text;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.Param;
import m.html.form.*;
import m.html.list.*;
import m.store.model.*;
import m.store.service.GoodsOutVirtualStockService;
import m.store.service.SaleInfoService;
import m.store.service.StoreNumberService;
import m.store.util.ColorUtil;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "store/saleInfo")
public class SaleInfoAction extends OrderModelAction {
    private SaleInfo model;
    private List<GoodsOutRecord> goodsList;
    private List<GoodsOutVirtualStock> virtualStocks;


    /**
     * 保存
     */
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "保存出库信息")
    public JSONMessage doSave() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(SaleInfoService.class).save(model,goodsList);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "保存并提交出库信息")
    public JSONMessage doSaveAndSubmit() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(SaleInfoService.class).saveAndSubmit(model,goodsList);
        return new JSONMessage(0,msg);
    }
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "保存虚拟库存")
    public JSONMessage doSaveVirtualStock() throws MException {
        getService(SaleInfoService.class).saveVirtualStock(virtualStocks);
        return new JSONMessage(0,"保存成功");
    }
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "保存虚拟库存并确认出库信息")
    public JSONMessage doSaveAndConfirm() throws Exception {
        getService(SaleInfoService.class).saveVirtualStock(virtualStocks);
        model=ModelQueryList.getModel(model,"*");
        getService(SaleInfoService.class).confirm(model,PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"提交成功");
    }
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "删除出库信息")
    public JSONMessage doDelete() throws Exception {
        getService(SaleInfoService.class).delete(model.getOid(),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"删除成功");
    }
    @RequestMeta(logTitle = "出库信息",logDescription = "审核通过出库信息")
    public JSONMessage doCheck() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Stock);
        //将虚拟库存生成调拨入库
        getService(GoodsOutVirtualStockService.class).convertGoodsStockRecord(model.getOid());
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            getService(SaleInfoService.class).check(model.getOid(),model.getSaleDate(),model.getRemark(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return new JSONMessage(0,"审核成功");
    }
    @RequestMeta(transaction = true,logTitle = "出库信息",logDescription = "提交出库信息")
    public JSONMessage doRefund() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Stock);
        getService(SaleInfoService.class).refund(model.getOid(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"退回成功");
    }
    /*
     * 编辑出库
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            goodsList=ModelQueryList.getModelList(GoodsOutRecord.class,new String[]{"*","record.*","record.goods.*"},null,
                    QueryCondition.eq("sale.oid",model.getOid()), QueryOrder.asc("oid"));
        }else{
            model=new SaleInfo();
            model.setOrderNo(StoreNumberService.getNextSaleNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(SaleInfo.Type_Sale);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setSaleDate(new Date());
            goodsList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Stock);

        ModelForm form = new ModelForm("出库信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.SaleInfo!type",ColorUtil.getSaleType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("出库单号","{{model.orderNo}}"),
            FormInput.selectOneModel("购货客户", "model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2).setEdit(edit),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("销售金额","<b>{{goodsList.length?formatNumber(model.saleAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormInput.date("出库日期","model.saleDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addButton(
            edit? FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,goodsList:this.goodsList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,goodsList:this.goodsList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("出库商品").setEdit(edit,true,"{record:{goods:{}},preferential:0}",false);
        form1.setData("goodsList",goodsList)
        .addMethod(
            FormEvent.custom("editRowAfter(item)",
                "item.saleAmount=this.roundNumber((item.price||0)*(item.num||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.saleAmount/(item.num||1),2);"
            ),
            FormEvent.custom("editDataAfter",
                "var sum=0.0;" +
                "for(var i=0;i<this.goodsList.length;i++){" +
                " sum+=(this.goodsList[i].saleAmount||0);" +
                "}" +
                "this.model.saleAmount=this.roundNumber(sum,2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("商品","record.goods.name",200)
                .setEdit(TableEdit.selectOneModel("'action/store/goodsStockRecord/selectStockList?params[virtualTab]=A'",1100,"record","goods.name")),
            TableGroup.ins("剩余",
                TableColumn.number("库存单价","record.preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.record.preferentialPrice,'#,##0.00')}}")),
                TableColumn.number("数量","record.surplusNum",80,"#,##0").isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.record.surplusNum,'#,##0')}}"))
            ),
            TableGroup.ins("出库",
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","num",80,"#,##0")
                    .setEdit(TableEdit.number("#,##0",0)),
                TableColumn.number("总优惠","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("优惠后",
                TableColumn.number("单价","preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.num-editRecord.preferential)/editRecord.num,'#,##0.00')}}")),
                TableColumn.number("金额","saleAmount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.num-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        result.addForm(form).addForm(form1);
        if(check && SaleInfo.Has_Yes.equals(model.getHasVirtualStock())){
            LoadPage virtualStockPage=new LoadPage("loadVirtualStockPage",actionUrl(GoodsOutVirtualStockAction.class,"recordList"),"{params:{'record.sale.oid':this.model.oid}}")
                    .setMounted("this.loadVirtualStockPage();");
            result.addForm(virtualStockPage);
        }
        return result;
    }
    public VueResult toEditRefund() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            goodsList=ModelQueryList.getModelList(GoodsOutRecord.class,new String[]{"*","record.*","record.goods.*"},null,
                    QueryCondition.eq("sale.oid",model.getOid()), QueryOrder.asc("oid"));
        }else if(null!=model&& ObjectUtil.notEmptyOid(model.getRefundStock())){
            if(!ModelQueryList.getModelList(SaleInfo.class, new String[]{"oid"}, null,
                QueryCondition.and(
                    QueryCondition.eq("refundStock.oid", model.getRefundStock().getOid()),
                    QueryCondition.not(QueryCondition.eq("status", OrderModel.Status_Done))
                )
            ).isEmpty()) throw new MException(this.getClass(),"已存在该订单未完成的退货，请到出库登记里查看。");
            model.setRefundStock(ModelQueryList.getModel(StockInfo.class,model.getRefundStock().getOid(),"*","guest.*"));
            model.setGuest(model.getRefundStock().getGuest());
            model.setOrderNo(StoreNumberService.getNextSaleNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(SaleInfo.Type_Refund);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setSaleDate(new Date());
            goodsList=new ArrayList<>();
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Stock);

        ModelForm form = new ModelForm("出库信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.SaleInfo!type",ColorUtil.getSaleType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("出库单号","{{model.orderNo}} "),
            FormHtml.inputStyle("购货客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("退货金额","<b>{{goodsList.length?formatNumber(model.saleAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormInput.date("退货日期","model.saleDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addButton(
            edit? FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,goodsList:this.goodsList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,goodsList:this.goodsList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("退货商品").setEdit(edit,true,"{record:{goods:{}},preferential:0}",false);
        form1.setData("goodsList",goodsList)
        .addMethod(
            FormEvent.custom("editRowAfter(item)",
             "item.saleAmount=this.roundNumber((item.price||0)*(item.num||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.saleAmount/(item.num||1),2);"
            ),
            FormEvent.custom("editDataAfter",
                "var sum=0.0;" +
                "for(var i=0;i<this.goodsList.length;i++){" +
                " sum+=(this.goodsList[i].saleAmount||0);" +
                "}" +
                "this.model.saleAmount=this.roundNumber(sum,2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("商品","record.goods.name",200)
                .setEdit(TableEdit.selectOneModel("'action/store/goodsStockRecord/selectStockList?params[stock.oid]="+model.getRefundStock().getOid()+"'",1100,"record","goods.name")),
            TableColumn.number("库存单价","record.preferentialPrice",100).isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.record.preferentialPrice,'#,##0.00')}}")),
            TableColumn.number("剩余数量","record.surplusNum",80,"#,##0").isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.record.surplusNum,'#,##0')}}")),
            TableGroup.ins("退货",
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","num",80,"#,##0")
                    .setEdit(TableEdit.number("#,##0",0)),
                TableColumn.number("总扣减","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("扣减后",
                TableColumn.number("单价","preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.num-editRecord.preferential)/editRecord.num,'#,##0.00')}}")),
                TableColumn.number("金额","saleAmount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.num-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    @RequestMeta(params = {"oper"})
    public VueResult toView(String oper) throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.name","inputUser.realname","checkUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
        }else{
            throw AuthInfoUtil.noPowerException;
        }
        boolean isSale=!SaleInfo.Type_Refund.equals(model.getType());
        ModelForm form = new ModelForm("库存信息");
        form.setSubTitle(ListElement.tag("model.type","m.store.model.SaleInfo!type",ColorUtil.getSaleType(),false).toString());
        form.addItem(
            FormHtml.inputStyle("出库单号", "{{model.orderNo}} {{dict('m.store.model.SaleInfo!status',model.status)}}"),
            FormHtml.inputStyle("登记人", "{{model.inputUser.realname}} {{formatDate(model.submitDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("审核人", "{{model.checkUser.realname}} {{formatDate(model.checkDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle(isSale?"出库日期":"退货日期","{{formatDate(model.saleDate,'yyyy-MM-dd')}}"),
            FormHtml.inputStyle("购货客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle(isSale?"销售金额":"退货金额", "{{formatNumber(model.saleAmount,'#,##0.00')}}")
        ).addMethod(
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        if(isSale){
            form.addItem(
                FormHtml.inputStyle("收款金额", "{{formatNumber(model.incomeAmount,'#,##0.00')}} {{dict('m.store.model.SaleInfo!incomeStatus',model.incomeStatus)}}"),
                FormHtml.inputStyle("尚欠金额","{{formatNumber(model.oweAmount,'#,##0.00')}}"),
                model.getRefundAmount()>0?FormHtml.inputStyle("退款金额", "{{formatNumber(model.refundAmount,'#,##0.00')}}"):null,
                FormHtml.inputStyle("备注","{{model.remark}}").setSpan(3)
            );
        }else{
            form.addItem(
                FormHtml.inputStyle("备注","{{model.remark}}").setSpan(2)
            );
        }
        form.addData("model",model);
        LoadPage recordPage=new LoadPage("loadRecordPage",actionUrl(GoodsOutRecordAction.class,"recordList"),"{params:{'oper':'"+oper+"','sale.oid':this.model.oid,'sale.type':'"+model.getType()+"'}}")
            .setMounted("this.loadRecordPage();");
        VueFormResult result=new VueFormResult();
        result.addForm(form).addForm(recordPage);
        if(SaleInfo.Has_Yes.equals(model.getHasVirtualStock())){
            LoadPage virtualStockPage=new LoadPage("loadVirtualStockPage",actionUrl(GoodsOutVirtualStockAction.class,"recordList"),"{params:{'record.sale.oid':this.model.oid}}")
                    .setMounted("this.loadVirtualStockPage();");
            result.addForm(virtualStockPage);
        }
        if(model.getRefundAmount()>0){
            LoadPage refundRecordPage=new LoadPage("loadRefundRecordPage",actionUrl(GoodsStockRecordAction.class,"refundRecordList"),"{params:{'stock.refundSale.oid':this.model.oid}}")
                .setMounted("this.loadRefundRecordPage();");
            result.addForm(refundRecordPage);
        }
        return result;
    }
    public VueResult toEditVirtualStock() throws Exception {
        virtualStocks=ModelQueryList.getModelList(GoodsOutVirtualStock.class,new String[]{"*","record.*","record.goods.*","record.record.stock.guest.*"},null,QueryCondition.eq("record.sale.oid",model.getOid()));
        TableForm form1=new TableForm("调货商品").setEdit(true);
        form1.setData("virtualStocks",virtualStocks)
        .addButton(
            FormButton.pri("保存","doSaveVirtualStock"),
            FormButton.succ("提交","doSaveAndConfirm").setConfirm("确定要提交吗？"),
            FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSaveVirtualStock",actionUrl("doSaveVirtualStock"),"{virtualStocks:this.virtualStocks}"),
            FormEvent.doJson("doSaveAndConfirm",actionUrl("doSaveAndConfirm"),"{model:this.model,virtualStocks:this.virtualStocks}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.custom("editRowAfter(item)",
            "item.stockAmount=this.roundNumber((item.price||0)*(item.stockNum||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.stockAmount/(item.stockNum||1),2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("调货客户","record.record.stock.guest.name",130)
                .setLink(FormEvent.toModal("viewGuest(record)",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:record.record.record.stock.guest.oid}}",1300)),
            TableColumn.text("出库商品","record.goods.name",170),
            TableGroup.ins("出库信息",
                TableColumn.number("单价","record.price",100).isSum(false),
                TableColumn.number("数量","record.num",80,"#,##0")
            ),
            TableGroup.ins("调货（请填写）",
                TableColumn.text("仓库","repository.oid",100)
                    .setShow(new Text("{{dict('m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid()+"',text)}}"))
                    .setEdit(TableEdit.select("m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid())),
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","stockNum",80,"#,##0"),
                TableColumn.number("总优惠","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("调货优惠后",
                TableColumn.number("单价","preferentialPrice",100)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.stockNum-editRecord.preferential)/editRecord.stockNum,'#,##0.00')}}")),
                TableColumn.number("金额","stockAmount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.stockNum-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form1)
            .addForm(
                new CustomForm(Element.tag("a-alert").A("message","可在下列商品全部调货成功后填写信息后再提交，审核通过后将生成调拨入库信息。"))
                    .addData("model",model)
            );
    }
    private ListColumn getTypeColumn(){
        String dict="m.store.model.SaleInfo!type";
        return toElementColumn("类型", "type", 100,
            ListElement.tag(dict, ColorUtil.getSaleType(),false)
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    /*
     * 我的出库列表列表
     */
    public VueResult myInputList() throws Exception {
        String month= DateUtil.format(new Date(),"yyyyMM");
        VueListResult result=getVueListResult("我的出库登记",SaleInfo.class,actionUrl("myInputList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("出库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("出库客户", "guest.name", 150, true));
        result.addCol(toDateColumn("出库日期", "saleDate", 100, true));
        result.addCol(toNumberColumn("销售金额", "saleAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.addCol(toTextColumn("收款状态", "incomeStatus", 100, true).setDictType("m.store.model.SaleInfo!incomeStatus"));
        result.addCol(toNumberColumn("收款金额", "incomeAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toSpaceColumn("操作", 140,
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'&&record.type=='"+SaleInfo.Type_Sale+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'&&record.type=='"+SaleInfo.Type_Refund+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEditRefund"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'",
                ListButton.ajax("删除", ButtonType.ERROR,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("确定要删除吗？")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Confirm+"'",
                ListButton.modal("调货提交", ButtonType.PRIMARY,actionUrl("toEditVirtualStock"),1400, SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Done+"'&&formatDate(record.saleDate,'yyyyMM')=='"+month+"'&&record.type=='"+SaleInfo.Type_Sale+"'",
                ListButton.page("登记退货", ButtonType.GHOST,actionUrl("toView"), SuccessMethod.MUST_REFRESH)
                    .addParam("model.oid","oid").addQueryParam(Param.value("oper","refund"))
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Done+"'&&formatDate(record.saleDate,'yyyyMM')!='"+month+"'&&record.type=='"+SaleInfo.Type_Sale+"'",
                ListButton.page("登记退货入库", ButtonType.GHOST,actionUrl(StockInfoAction.class,"toEditRefund"), SuccessMethod.REFRESH)
                    .addParam("model.refundSale.oid","oid")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.page("登记出库", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
        );
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("出库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库日期","saleDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUser(true).getOid()));
        return result;
    }
    /*
     * 待审核列表
     */
    public VueResult checkList() throws Exception {
        VueListResult result=getVueListResult("出库待审核",SaleInfo.class,actionUrl("checkList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("出库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("出库客户", "guest.name", 150, true));
        result.addCol(toDateColumn("出库日期", "saleDate", 100, true));
        result.addCol(toNumberColumn("销售金额", "saleAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        fillOrderColumn(result);
        if(PowerUtil.hasPower(PowerUtil.Stock)) {
            result.addCol(toSpaceColumn("操作", 100,
                ListElement.test("record.type=='"+StockInfo.Type_Stock+"'",
                    ListButton.page("审核", ButtonType.PRIMARY, actionUrl("toEdit"),  SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid")
                ),
                ListElement.test("record.type=='"+StockInfo.Type_Refund+"'",
                    ListButton.page("退货审核", ButtonType.PRIMARY, actionUrl("toEditRefund"),  SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid")
                )
            ).setFixed(Align.RIGHT));
        }
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("出库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库日期","saleDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("status",OrderModel.Status_Check));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    public VueResult selectOneChecked() throws Exception {
        String selected=getParamsValue("selected","");
        VueListResult result=getVueListResult("选择出库订单",SaleInfo.class,actionUrl("selectOneChecked"));
        result.addQueryFields("oid");
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("出库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toDateColumn("出库日期", "saleDate", 100, true));
        result.addCol(toNumberColumn("销售金额", "saleAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        fillOrderColumn(result);
        result.addCol(toSpaceColumn("操作", 100,
            ListElement.test("record.oid!='"+selected+"'",
                ListButton.back("选择", ButtonType.PRIMARY)
                    .addParam("","")
            ),
            ListElement.elseOther(ListElement.tag("已选",""))
        ).setFixed(Align.RIGHT));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addSearch(ListSearch.field("客户","guest.oid",SearchType.HIDDEN_EQ));
        result.addCondition(QueryCondition.eq("status", OrderModel.Status_Done));
        result.addCondition(QueryCondition.in("type",SaleInfo.Type_Sale,SaleInfo.Type_Refund));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oweAmount",0)));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUserOid()));
        return result;
    }

    public VueResult queryList() throws Exception {
        VueListResult result = getVueListResult("出库订单查询", SaleInfo.class, actionUrl("queryList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("出库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL, 1200)
                .addParam("model.oid", "oid")
        ));
        result.addCol(toTextColumn("出库客户", "guest.name", 150, true));
        result.addCol(toDateColumn("出库日期", "saleDate", 100, true));
        result.addCol(toNumberColumn("销售金额", "saleAmount", 100, true));
        result.addCol(toTextColumn("备注", "remark", 150, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("出库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库日期","saleDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    public VueResult noSettleList() throws Exception {
        VueListResult result = getVueListResult("应收出库订单", SaleInfo.class, actionUrl("noSettleList"));
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("出库单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL, 1200)
                .addParam("model.oid", "oid")
        ));
        result.addCol(toTextColumn("出库客户", "guest.name", 150, true));
        result.addCol(toDateColumn("出库日期", "saleDate", 100, true));
        result.addCol(toNumberColumn("销售金额", "saleAmount", 100, true));
        result.addCol(toTextColumn("收款状态", "incomeStatus", 100, true).setDictType("m.store.model.SaleInfo!incomeStatus"));
        result.addCol(toNumberColumn("收款金额", "incomeAmount", 100, true));
        result.addCol(toNumberColumn("尚欠金额", "oweAmount", 100, true));
        result.addCol(toTextColumn("备注", "remark", 150, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("出库单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("出库日期","saleDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oweAmount",0)));
        return result;
    }
    public SaleInfo getModel() {
        return model;
    }

    public void setModel(SaleInfo model) {
        this.model = model;
    }

    public List<GoodsOutRecord> getGoodsList() {
        return goodsList;
    }

    public void setGoodsList(List<GoodsOutRecord> goodsList) {
        this.goodsList = goodsList;
    }

    public List<GoodsOutVirtualStock> getVirtualStocks() {
        return virtualStocks;
    }

    public void setVirtualStocks(List<GoodsOutVirtualStock> virtualStocks) {
        this.virtualStocks = virtualStocks;
    }
}
